package com.ppo.test.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class TimeoutCall {

	private static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool();

	private static <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
	    FutureTask<T> task = new FutureTask<T>(c);
	    THREAD_POOL.execute(task);
	    
	    T value = null;
		try {
			value = task.get(timeout, timeUnit);
		} catch (TimeoutException e) {
			task.cancel(true);
			throw e;
		}
	    return value;
	}


	public static void main(String[] args) {

		try {
		    int returnCode = timedCall(new Callable<Integer>() {
		        public Integer call() throws Exception {
		        	for (int i=0; i < 100; i++) {
		        		System.out.println(new java.util.Date());
		        		Thread.sleep(1000);
		        	}
		    		return 0;
		        }
		    }, 10, TimeUnit.SECONDS);
		    System.out.println("return value:" + returnCode);
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}


	}

}
